import { getContent } from '@/api/content'

const buildContent = (h, contents) => {
  return contents.map((c) => {
    if (typeof c === 'string') {
      return c
    }

    let children = ''
    if (c.contents && c.contents.length > 0) {
      children = buildContent(h, c.contents)
    }

    return h(c.component, {
      props: c.props,
      class: c.class,
    }, [children])
  })
}

export default {
  name: 'Content',
  render(h) {
    const data = this.data

    let header = ''
    let body = ''

    if (data) {
      const title = data.title ? h('span', { class: { title: true } }, data.title) : ''
      const desc = data.desc ? h('span', { class: { desc: true } }, data.desc) : ''
      if (data.contents && data.contents.length > 0) {
        body = buildContent(h, data.contents)
      }

      header = h('p', {
        class: {
          'content-header': true,
        },
      }, [title, desc])
    }

    body = body
      ? h('div', {
        class: {
          'content-body': true,
        },
      }, [body])
      : ''

    return h(
      'div',
      {
        class: {
          'app-container': true,
        },
      },
      this.loading ? [h('content-loading')] : [header, body],
    )
  },
  data() {
    return {
      data: null,
      loadingLayer: null,
      loading: true,
    }
  },
  methods: {
    load() {
      this.loaded()
      // 没有内容时,避免出现全屏的loading框
      if (!this.data) {
        return
      }
      this.loadingLayer = this.$loading({
        lock: true,
        target: '.content-body',
        background: 'rgba(255, 255, 255, 0.6)',
      })
    },
    loaded() {
      this.loadingLayer && this.loadingLayer.close()
      this.loadingLayer = null
    },

    getContent() {
      this.load()

      getContent(this.$route.fullPath)
        .then((res) => {
          const data = res.data
          this.data = null
          this.loaded()
          this.loading = false
          if (data.status) {
            this.data = data.content
          }
        })
        .catch(() => {
          this.data = null
          this.loaded()
          this.loading = false
        })
    },
  },
  watch: {
    $route: {
      handler() {
        this.getContent()
      },
      immediate: true,
    },
  },
}
